<template>
  <div class="chart-container">
    <el-form ref="roleRef2" :model="form2" label-width="120px">
      <chart :options="chartOptions" height="350px" />
      <el-row style="width: 1200px;;margin-top: 80px;">
        <el-col :span="6">
          <el-form-item label="A相电压">
            <el-input v-model.trim="form2.ua" boe readonly maxlength="30" placeholder="-" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="A相电压状态">
            <el-input :value="getVoltageStatus(form2.ua_st)" readonly maxlength="30" placeholder="-" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="B相电压">
            <el-input v-model.trim="form2.ub" readonly maxlength="30" placeholder="-" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="B相电压状态">
            <el-input :value="getVoltageStatus(form2.ub_st)" readonly maxlength="30" placeholder="-" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="C相电压">
            <el-input v-model.trim="form2.uc" readonly maxlength="30" placeholder="-" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="C相电压状态">
            <el-input :value="getVoltageStatus(form2.uc_st)" readonly maxlength="30" placeholder="-" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="3U0电压">
            <el-input v-model.trim="form2.u0" readonly maxlength="30" placeholder="-" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="3U0电压状态">
            <el-input :value="getVoltageStatus(form2.u0_st)" readonly maxlength="30" placeholder="-" />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
          <el-form-item label="告警时间" v-if="form2.ts">
            <el-input v-model.trim="form2.ts" readonly maxlength="30" placeholder="-" />
          </el-form-item>
        </el-col> -->
      </el-row>
    </el-form>
  </div>
</template>

<script setup>
/**
 * 故障波形图表展示组件
 * 包含两个图表：
 * 1. 主图表：显示A、B、C相电压和零线电压的波形
 */
// 引入必要的组件和API
import { useDark, useToggle } from '@vueuse/core'
const isDark = useDark()
const isDarkMode = useDark()
import chart from '@/components/chart';
const route = useRoute();
const { proxy } = getCurrentInstance();
// 显示加载提示
proxy.$modal.loading("正在加载...");
const form2 = ref({
  id: null,
  ua: null,
  ua_st: null,
  ub: null,
  ub_st: null,
  over: null,
  uc: null,
  uc_st: null,
  u0: null,
  u0_st: null,
  ts: null,
})
const dataInfo = ref({})
const id = ref(null);
const chartOptions = ref({
  title: {
    text: '',
    left: 'center',
    textStyle: {
      color: '#ff0000',
      fontSize: 22,
    },
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'line',
      lineStyle: {
        color: '#FF0000',    // 指示器线条颜色设置为红色
        width: 1,            // 线条宽度
      }
    },
    formatter: function (params) {
      // let result = params[0].name + '<br/>';
      let result = '';
      params.forEach(param => {
        if (param.seriesName == '3U0电压') {
          result += param.seriesName + ': ' + param.value + 'V<br/>';
        } else {
          // 使用 toFixed(2) 确保结果最多两位小数
          result += param.seriesName + ': ' + Math.round(param.value * 100) + 'V<br/>';
        }
      });
      return result;
    }
  },
  legend: {
    type: 'scroll',
    top: '8%',
    left: 'center',
    textStyle: {
      color: '#333'
    },
    data: ['A相电压', 'B相电压', 'C相电压', '3U0电压'],
    selected: {
      'A相电压': true,
      'B相电压': true,
      'C相电压': true,
      '3U0电压': true
    }
  },
  color: ['#FFFF00', '#00FF00', '#FF0000', '#0000FF'],
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    show: true,
    data: [],
    axisLabel: {
      interval: function (index, total) {
        return total;
      }
    }
  },
  yAxis: {
    type: 'value',
    name: '电压(V)',
    splitLine: {
      lineStyle: {
        type: 'dashed'
      }
    },
    axisLabel: {
      formatter: '{value}'
    }
  },
  series: []
});
  // 监听主题变化
  watch(isDarkMode, (newIsDarkMode) => {
    const textColor = newIsDarkMode ? '#fff' : '#333';
    // 更新主图表文字颜色
    // chartOptions.value.title.textStyle.color = textColor;
    chartOptions.value.legend.textStyle.color = textColor;
  }, { immediate: true });

// 组件挂载时初始化图表数据
// 在 onMounted 钩子的开始处添加
onMounted(() => {
  const chartContainer = document.querySelector('.chart-container');
  if (chartContainer) {
    chartContainer.addEventListener('mousewheel', () => { }, { passive: true });
  }
  proxy.cloudTv_API.FindOneAlarm({
    id: route.query.id,
  }).then(res => {
    const mes = JSON.parse(res.data.mes);
    dataInfo.value = res.data;
    form2.value = mes;
    const data = {
      series: [
        { name: 'A相电压', data: res.data.ua_wave.split(',') },
        { name: 'B相电压', data: res.data.ub_wave.split(',') },
        { name: 'C相电压', data: res.data.uc_wave.split(',') },
        { name: '3U0电压', data: res.data.u0_wave.split(',') },
      ]
    };
    console.log(data);
    
    // 获取 A 相电压数据长度作为基准，假设各相数据长度一致
    const dataLength = res.data.ua_wave.split(',').length;
    const xAxisData = new Array(dataLength).fill('');
    // 计算每组的间隔点数
    const intervalPoints = Math.floor((dataLength - 1) / 12);
    // 动态为 xAxisData 赋值
    for (let i = 0; i < 12; i++) {
      const index = i * intervalPoints;
      xAxisData[index] = `${-80 + i * 20}(ms)`;
    }
    // 确保最后一个点显示 160(ms)
    if (dataLength > 0) {
      xAxisData[dataLength - 1] = '160(ms)';
    }
    xAxisData[dataLength - 1] = '160(ms)';
    const { alarmtime , type } = route.query;
    chartOptions.value.title.text = `${type} — ${dataInfo.value.dev_id} — ${alarmtime}`;
    chartOptions.value.xAxis.data = xAxisData;
    chartOptions.value.series = data.series.map(item => ({
      name: item.name,
      type: 'line',
      smooth: false,
      symbol: 'circle',
      symbolSize: 0,
      data: item.data,
      itemStyle: {
        normal: {
          lineStyle: {
            width: 1
          }
        }
      }
    }));
    
  }).finally(() => {
      proxy.$modal.closeLoading();
    });

});
// 电压状态映射函数
const getVoltageStatus = computed(() => (status) => {
  const statusMap = {
    'nromal': '正常',
    'over': '超压',
    'drop': '欠压',
    'zero': '失压/为零'
  };
  return statusMap[status] || status;
});
</script>

<style lang="scss" scoped>
.chart-container {
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  height: calc(100vh - 84px);
  overflow-y: auto;

  .mt20 {
    margin-top: 20px;
  }
}
</style>